package com.vhall.component.service.rbac;

import com.alibaba.fastjson.JSON;
import com.vhall.component.entity.rbac.vo.ActionsVO;
import com.vhall.component.entity.rbac.vo.RoleVO;
import com.vhall.component.framework.common.utils.StringUtils;
import com.vhall.component.plugin.common.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author yongzheng.xu
 * @date 2021/8/12 18:39
 */
@Slf4j
@Component
public class RbacInitialization {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RbacRoleService rbacRoleService;

    @Autowired
    private RbacRoleActionService roleActionService;

    /**
     * 初始化角色数据
     */
    @PostConstruct
    public void initActionCache() {
        try {
            log.warn("========> 初始化角色权限信息 start");
            List<RoleVO> roles = rbacRoleService.listAllRole();
            for (RoleVO role : roles) {
                doInit(role.getRoleId());
            }
            log.warn("========> 初始化角色权限信息 ends");
        } catch (Exception ex) {
            throw ex;
        }
    }

    public void doInit(Integer roleId) {
        try {
            List<ActionsVO> actions = roleActionService.listActionByRoleId(roleId);
            Set<String> perm = new HashSet<>();
            for (ActionsVO action : actions) {
                if (StringUtils.isNotEmpty(action.getActionTag())) {
                    perm.add(action.getActionTag());
                }
            }
            String key = RedisKey.ROLE_PERMISSION + roleId;
            redisTemplate.opsForValue().set(key, JSON.toJSONString(perm));
        } catch (Exception ex) {
            throw ex;
        }
    }
}
